# app/core/logging_config.py
import os
import re
import logging
import time
import datetime
from logging.handlers import TimedRotatingFileHandler
from flask import request, g

# 日志配置常量
LOG_FORMAT = '%(asctime)s [%(levelname)s] [%(ip)s] [%(user_agent)s] %(message)s'
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
LOG_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'logs')
LOG_FILE = os.path.join(LOG_DIR, 'app.log')
LOG_LEVEL = logging.INFO

# 敏感信息匹配模式
SENSITIVE_PATTERNS = [
    # API密钥
    (r'(api[-_]?key|apikey|key)[\s]*[=:]["\s]*([\w\-\.]+)', r'\1=***'),
    # 手机号
    (r'(1[3-9]\d{9})', r'***\1[-4:]'),
    # 电话号码
    (r'(\d{3,4}-\d{7,8})', r'***-***'),
    # 邮箱
    (r'([\w\.-]+)@([\w\.-]+)', r'***@\2'),
    # 身份证号
    (r'(\d{17}[\dxX]|\d{15})', r'***'),
    # 姓名(中文姓名通常是2-4个汉字)
    (r'([\u4e00-\u9fa5]{2,4})', r'*' * len(r'\1') if len(r'\1') > 0 else r'\1')
]

class SensitiveFilter(logging.Filter):
    """过滤敏感信息的日志过滤器"""
    
    def filter(self, record):
        if not hasattr(record, 'msg') or not record.msg:
            return True
            
        # 如果记录是字符串，过滤敏感信息
        if isinstance(record.msg, str):
            for pattern, replacement in SENSITIVE_PATTERNS:
                try:
                    record.msg = re.sub(pattern, replacement, record.msg)
                except Exception:
                    pass
                    
        # 添加请求相关信息
        record.ip = self._get_client_ip()
        record.user_agent = self._get_user_agent()
        
        return True
    
    def _get_client_ip(self):
        """获取客户端IP地址"""
        if not request:
            return '-'
            
        # 考虑各种代理情况获取真实IP
        if request.headers.get('X-Forwarded-For'):
            # 使用X-Forwarded-For的第一个IP（真实客户端IP）
            return request.headers.get('X-Forwarded-For').split(',')[0].strip()
        elif request.headers.get('X-Real-IP'):
            return request.headers.get('X-Real-IP')
        else:
            return request.remote_addr or '-'
    
    def _get_user_agent(self):
        """获取用户代理信息"""
        if not request:
            return '-'
        return request.headers.get('User-Agent', '-')

def setup_logging():
    """设置应用日志"""
    # 确保日志目录存在
    os.makedirs(LOG_DIR, exist_ok=True)
    
    # 配置根日志器
    logger = logging.getLogger()
    logger.setLevel(LOG_LEVEL)
    
    # 清除现有处理器
    if logger.handlers:
        for handler in logger.handlers:
            logger.removeHandler(handler)
    
    # 创建控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(LOG_LEVEL)
    console_formatter = logging.Formatter(LOG_FORMAT, DATE_FORMAT)
    console_handler.setFormatter(console_formatter)
    
    # 创建文件处理器（每天轮转，保留7天）
    file_handler = TimedRotatingFileHandler(
        LOG_FILE, 
        when='midnight',
        interval=1,
        backupCount=7,
        encoding='utf-8'
    )
    file_handler.setLevel(LOG_LEVEL)
    file_formatter = logging.Formatter(LOG_FORMAT, DATE_FORMAT)
    file_handler.setFormatter(file_formatter)
    
    # 添加敏感信息过滤器
    sensitive_filter = SensitiveFilter()
    file_handler.addFilter(sensitive_filter)
    console_handler.addFilter(sensitive_filter)
    
    # 添加处理器到日志器
    logger.addHandler(console_handler)
    logger.addHandler(file_handler)
    
    # 设置Flask日志器
    flask_logger = logging.getLogger('werkzeug')
    flask_logger.setLevel(LOG_LEVEL)
    for handler in flask_logger.handlers:
        flask_logger.removeHandler(handler)
    flask_logger.addHandler(console_handler)
    flask_logger.addHandler(file_handler)
    
    logging.info("日志系统初始化完成")
    return logger 